import {defineStore} from 'pinia'
import {getUserId, connect, disconnect} from '@/utils/websocket.js'
import {SubType, MessageType} from '@/constants/message.js'
import {ElMessageBox, ElNotification} from 'element-plus'
import {WsRoute} from '@/constants/routes.js'
import {buildRoute} from '@/utils/route'
import useUserStore from "@/store/modules/user.js";
import {handleAppointmentEnd} from "@/api/websocket/websocket.js";

export const useWebSocketStore = defineStore('websocket', {
    state: () => ({
        stompClient: null,
        subscriptions: [],
        approvalRequests: [],
        approvalResults: [],
        systemMessages: {
            all: [],
            admin: []
        },
        chatMessages: new Map(),
        currentAppointmentEnd: null
    }),

    actions: {
        // 完整的连接初始化方法
        async initConnection() {
            try {
                // 先断开旧连接
                if (this.stompClient) {
                    await this.disconnect()
                }

                // 建立新连接
                this.stompClient = await connect()
                if (!this.stompClient?.connected) {
                    throw new Error('STOMP 连接未正确建立')
                }

                const userId = getUserId()
                console.log('🔌 新连接建立，用户ID:', userId)

                const userStore = useUserStore();
                const role = userStore.roles[0];
                console.log('用户角色：', role)

                const formatRoute = (route, userId) => route.replace('%s', userId);

                // 系统通知（公共部分保留）
                const baseSubscriptions = [{
                    route: WsRoute.SYSTEM_TOPIC,
                    handler: this.handleSystemMessage
                }];

                const roleSpecificSubs = [];
                roleSpecificSubs.push(
                    // {route: formatRoute(WsRoute.USER_CHAT_QUEUE, userId), handler: this.handleUserChat},
                    {route: formatRoute(WsRoute.USER_APPROVAL_RESULT_QUEUE, userId), handler: this.handleAdminResult},
                    {route: formatRoute(WsRoute.USER_CONSULTATION_QUEUE, userId), handler: this.handleConsultation},
                    {
                        route: formatRoute(WsRoute.USER_APPOINTMENT_RESULT_QUEUE, userId),
                        handler: this.handleAppointmentResult
                    },
                );

                // 订阅配置
                const subscriptionsConfig = [...baseSubscriptions, ...roleSpecificSubs]
                console.log('订阅配置:', subscriptionsConfig)
                // 生成订阅列表
                this.subscriptions = subscriptionsConfig.map(config => {
                    const destination = config.route.includes('%s')
                        ? buildRoute(config.route, userId)
                        : config.route
                    return this.subscribeWithLog(destination, config.handler)
                })

                console.log('WebSocket 初始化完成')
            } catch (error) {
                console.error('连接初始化失败:', error)
                throw error
            }
        },

        // 订阅工具方法
        subscribeWithLog(destination, handler) {
            const sub = this.stompClient.subscribe(destination, message => {
                console.log(`[WS] 收到 ${destination} 消息`, JSON.parse(message.body))
                try {
                    const msg = JSON.parse(message.body)
                    this.validateMessage(msg) // 新增校验
                    handler.call(this, msg)
                } catch (error) {
                    console.error('消息处理失败:', error)
                }
            })
            console.log(`[WS] 已订阅 ${destination}`)
            return sub
        },

        // 断开连接
        async disconnect() {
            if (this.stompClient?.connected) {
                await disconnect()
                this.subscriptions.forEach(sub => sub.unsubscribe())
                this.stompClient = null
                console.log('WebSocket 已断开')
            }
        },

        // 显示预约结果通知
        showAppointmentNotification(message) {
            console.log('显示预约结果通知', message)
            ElNotification({
                title: message.title || '预约结果通知',
                message: message.message || '您有一条新的预约结果',
                type: message.type || 'info',
                duration: 5000
            })
        },

        // 咨询师预约结果处理
        handleAppointmentResult(message) {
            console.log("进入预约结果方法")
            if (!this.validateMessageType(message, MessageType.APPOINTMENT_MSG)) {
                return
            }
            console.log('咨询师审批结果处理', message)
            switch (message.subType) {
                case SubType.APPOINTMENT.RESULT:
                    // this.systemMessages.admin.push(message)
                    this.showAppointmentNotification({
                        title: '预约结果处理',
                        message: message.content,
                        type: 'info'
                    })
                    break
                case SubType.APPOINTMENT.END:
                    this.showAppointmentEndConfirm({
                        title: '咨询结束通知',
                        message: message.content,
                        type: 'info',
                        senderId: message.senderId,
                        receiverId: message.receiverId
                    })
                    break
                default:
                    console.warn('未知消息类型', message)
            }
        },

        // 咨询结束确认
        showAppointmentEndConfirm(message) {
            console.log('显示咨询结束确认', message)
            ElMessageBox.confirm(message.message, message.title, {
                confirmButtonText: '确定',
                type: 'warning'
            }).then(() => {
                handleAppointmentEnd(message.senderId,message.receiverId)
            }).catch(() => {
                console.log('用户点击取消')
            })
        },

        // 管理员审批结果处理
        handleAdminResult(message) {
            if (!this.validateMessageType(message, MessageType.APPROVAL_MSG)) {
                return
            }
            if (message.subType === SubType.APPROVAL.RESULT) {
                this.systemMessages.all.push(message)
                ElNotification({
                    title: '系统通知',
                    message: message.content,
                    type: 'info'
                })
            } else {
                console.warn('未知系统消息类型', message)
            }
        },

        // 用户私聊处理
        handleUserChat(message) {
            this._processChatMessage(message, SubType.CHAT.USER_TO_USER)
        },

        // 咨询会话处理
        handleConsultation(message) {
            this._processChatMessage(message, SubType.CHAT.USER_TO_CONSULTANT)
        },

        // 统一聊天处理逻辑
        _processChatMessage(message, expectedSubType) {
            console.log('原始消息:', JSON.parse(JSON.stringify(message)))
            if (message.subType !== expectedSubType) {
                console.warn(`消息类型不匹配，期望 ${expectedSubType}，收到 ${message.subType}`)
                return
            }

            const participants = [
                Number(message.senderId),
                Number(message.receiverId)
            ].sort((a, b) => a - b)
            const chatId = participants.join('_')
            console.log('生成chatId:', chatId)
            // 发送方处理
            if (message.senderId === getUserId()) {
                const tempMessage = this.findTempMessage(chatId, message)
                if (tempMessage) {
                    this.replaceTempMessage(tempMessage.tempId, message)
                    return
                }
                return
            }

            // 接收方处理
            this.mergeHistoryMessages(chatId, [{
                ...message,
                status: 'success',
                isConsultation: expectedSubType === SubType.CHAT.USER_TO_CONSULTANT
            }])

            this.chatMessages = new Map(this.chatMessages)
        },

        // 消息校验
        validateMessage(message) {
            const requiredFields = ['type', 'subType', 'content']
            const missingFields = requiredFields.filter(field => !message[field])
            if (missingFields.length > 0) {
                throw new Error(`store消息缺少必要字段: ${missingFields.join(', ')}`)
            }
        },

        // 处理系统消息
        handleSystemMessage(message) {
            if (!this.validateMessageType(message, MessageType.SYSTEM_MSG)) {
                return
            }
            switch (message.subType) {
                case SubType.SYSTEM.BROADCAST:
                    this.systemMessages.all.push(message)
                    ElNotification({
                        title: '系统通知',
                        message: message.content,
                        type: 'info'
                    })
                    break
                default:
                    console.warn('未知系统消息类型', message)
            }
        },

        // 类型校验工具
        validateMessageType(message, expectedType) {
            if (message.type !== expectedType) {
                console.error(`消息类型错误，期望 ${expectedType}，收到 ${message.type}`)
                return false
            }
            return true
        },

        // 发送消息
        async sendMessage(payload) {
            const baseMessage = {
                senderId: getUserId(),
                sendTime: new Date().toISOString(),
                isRead: '0',
                delFlag: '0'
            }

            const tempId = `client_${Date.now()}`;
            const tempMessage = {
                ...baseMessage,
                ...payload,
                tempId,
                status: 'sending',
                receiverId: Number(payload.receiverId),
                relatedId: payload.relatedId ? Number(payload.relatedId) : null
            }

            // 增强校验
            const requiredFields = ['type', 'subType', 'receiverId', 'content']
            const missingFields = requiredFields.filter(field => !tempMessage[field])
            if (missingFields.length > 0) {
                console.error('消息缺少必要字段:', missingFields)
                return false
            }

            try {
                this.addTempMessage(tempMessage)
                const {tempId: _, status: __, ...sendPayload} = tempMessage
                await this._sendRawMessage(sendPayload)
                return true
            } catch (error) {
                this.updateMessageStatus(tempId, 'failed')
                throw error
            }
        },

        // 底层发送方法
        _sendRawMessage(payload) {
            return new Promise((resolve, reject) => {
                if (!this.stompClient?.connected) {
                    reject(new Error('STOMP 连接未就绪'))
                    return
                }

                try {
                    this.stompClient.publish({
                        destination: '/app/chat.send',
                        body: JSON.stringify(payload),
                        headers: {'Content-Type': 'application/json'}
                    })
                    resolve()
                } catch (error) {
                    console.error('发送失败', {
                        error: error.message,
                        payload
                    })
                    reject(error)
                }
            })
        },

        // 以下辅助方法保持不变
        findTempMessage(chatId, message) {
            const messages = this.chatMessages.get(chatId) || []
            return messages.find(m =>
                !m.messageId &&
                m.content === message.content &&
                Math.abs(new Date(m.sendTime) - new Date(message.sendTime)) < 2000
            )
        },

        addTempMessage(message) {
            const participants = [
                Number(message.senderId),
                Number(message.receiverId)
            ].sort((a,b)=>a-b)
            const chatId = participants.join('_')
            console.log('📤 存储临时消息到:', chatId, '消息内容:', message.content)
            if (!this.chatMessages.has(chatId)) {
                this.chatMessages.set(chatId, [])
            }
            this.chatMessages.get(chatId).push(message)
        },

        replaceTempMessage(tempId, confirmedMessage) {
            const participants = [
                Number(confirmedMessage.senderId),
                Number(confirmedMessage.receiverId)
            ].sort((a, b) => a - b)
            const chatId = participants.join('_')
            console.log('🔄 替换消息路径:', chatId, '临时ID:', tempId)

            const messages = this.chatMessages.get(chatId) || []
            const index = messages.findIndex(m => m.tempId === tempId)
            if (index !== -1) {
                messages.splice(index, 1, {
                    ...confirmedMessage,
                    status: 'success'
                })
            }
        },

        updateMessageStatus(tempId, status) {
            for (const [chatId, messages] of this.chatMessages) {
                const msg = messages.find(m => m.tempId === tempId)
                if (msg) {
                    msg.status = status
                    break
                }
            }
        },

        mergeHistoryMessages(chatId, newMessages) {
            const normalizedChatId = chatId.split('_')
                .map(id => parseInt(id, 10))
                .sort((a, b) => a - b)
                .join('_')
            console.log('🔀 合并消息 | 原始chatId:', chatId, '标准化后:', normalizedChatId)
            if (chatId !== normalizedChatId) {
                console.log('⚠️ 检测到不一致的chatId，执行数据迁移')
                const oldMessages = this.chatMessages.get(chatId) || []
                this.chatMessages.set(normalizedChatId, [...oldMessages, ...newMessages])
                this.chatMessages.delete(chatId) // 清理旧数据
                return
            }

            const existing = this.chatMessages.get(chatId) || [];

            // 创建三层消息映射
            const tempMsgMap = new Map();  // 临时消息 (status: sending/failed)
            const liveMsgMap = new Map();  // 已确认的实时消息
            const historyMsgMap = new Map(); // 历史消息

            // 分类现有消息
            existing.forEach(msg => {
                const key = this._createHistoryKey(msg);
                if (msg.status && msg.status !== 'success') {
                    tempMsgMap.set(msg.tempId, msg);
                } else if (msg.isHistory) {
                    historyMsgMap.set(key, msg);
                } else {
                    liveMsgMap.set(key, msg);
                }
            });

            // 合并新消息（保留历史消息标记）
            newMessages.forEach(msg => {
                const key = this._createHistoryKey(msg);
                if (!historyMsgMap.has(key)) {
                    historyMsgMap.set(key, {...msg, isHistory: true});
                }
            });

            // 最终合并：临时消息 + 实时消息 + 历史消息
            const merged = [
                ...tempMsgMap.values(),
                ...liveMsgMap.values(),
                ...historyMsgMap.values()
            ].sort((a, b) => new Date(a.sendTime) - new Date(b.sendTime));

            this.chatMessages.set(chatId, merged);
        },
        _createHistoryKey(msg) {
            return `${msg.senderId}_${msg.sendTime}_${msg.content}`.replace(/\s+/g, '');
        }
    }
})
